<template>
  <el-dialog v-bind="$attrs" width="500" title="注册账号">
    <div class="form-content">
      <el-form
        ref="formRef"
        :model="formData"
        label-width="70px"
        :rules="formRule"
        size="large"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="formData.username" placeholder="请输入账号"></el-input>
        </el-form-item>
        <el-form-item label="密 码" prop="password">
          <el-input v-model="formData.password" placeholder="请输入密码"></el-input>
        </el-form-item>
        <el-form-item label="验证码" prop="captcha">
          <el-row :gutter="10">
            <el-col :span="15">
              <el-input
                style="width: 100%"
                v-model="formData.captcha"
                placeholder="请输入验证码"
              ></el-input>
            </el-col>
            <el-col :span="9">
              <img
                @click="emit('refresh')"
                style="width: 100%; height: 44px; cursor: pointer"
                :src="captcha"
                alt="验证码"
              />
            </el-col>
          </el-row>
        </el-form-item>
      </el-form>
    </div>
    <div slot="footer" class="dialog-footer">
      <el-button @click="cancel">取消</el-button>
      <el-button type="primary" @click="confirm">确定</el-button>
    </div>
  </el-dialog>
</template>

<script setup lang="ts">
import { markRaw, ref } from 'vue'
import { ElMessage, FormInstance } from 'element-plus'
import { registerUserApi } from '@/api/modules/user'
import { UniCloudSentence } from '@/enums/uniCloud'

defineProps(['captcha'])
const emit = defineEmits(['finish', 'update:modelValue', 'refresh'])
const formRef = ref<FormInstance>()

let defaultFormData = {
  username: 'mo',
  password: 'mo123456...',
  captcha: ''
}
const formData = ref({ ...defaultFormData })
const formRule = markRaw({
  username: [{ required: true, message: '请输入账号', trigger: 'blur' }],
  password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
  captcha: [{ required: true, message: '请输入验证码', trigger: 'blur' }]
})
const cancel = () => {
  emit('update:modelValue', false)
  formRef.value?.clearValidate()
}
const confirm = () => {
  formRef.value?.validate(async (valid) => {
    if (valid) {
      console.log(formData.value)
      let res = await registerUserApi({ params: formData.value })
      if (res.errCode === 0) {
        ElMessage.success('注册成功')
        emit('update:modelValue', false)
      } else {
        emit('refresh')
        formData.value.captcha = ''
        ElMessage.error(UniCloudSentence[res.errCode])
      }
    }
  })
}
</script>

<style lang="scss" scoped>
.form-content {
  padding: 20px;
}

.dialog-footer {
  padding: 5px 20px;
  text-align: right;
}
</style>
